<template>
  <div class="product-manage">
    <h1 class="page-title">产品管理</h1>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品管理</span>
          <el-button type="primary" @click="handleAdd">添加产品</el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filter-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索产品名称"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterCategory" placeholder="筛选分类" style="width: 200px" clearable @change="handleFilter">
          <el-option label="全部" value="" />
          <el-option label="美妆" value="makeup" />
          <el-option label="服饰" value="clothing" />
          <el-option label="数码" value="digital" />
          <el-option label="电器" value="appliance" />
          <el-option label="生鲜" value="fresh" />
          <el-option label="户外" value="outdoor" />
        </el-select>
      </div>

      <!-- 产品表格 -->
      <el-table :data="filteredProducts" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag>{{ getCategoryName(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">¥{{ row.price }}</template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredProducts.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="美妆" value="makeup" />
            <el-option label="服饰" value="clothing" />
            <el-option label="数码" value="digital" />
            <el-option label="电器" value="appliance" />
            <el-option label="生鲜" value="fresh" />
            <el-option label="户外" value="outdoor" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="图片URL" prop="image">
          <el-input v-model="form.image" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入产品描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const loading = ref(false)
const products = ref([])
const searchKeyword = ref('')
const filterCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogTitle = ref('添加产品')
const formRef = ref()
const editingId = ref(null)

const form = ref({
  name: '',
  category: '',
  price: 0,
  image: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}

const categoryMap = {
  makeup: '美妆',
  clothing: '服饰',
  digital: '数码',
  appliance: '电器',
  fresh: '生鲜',
  outdoor: '户外'
}

const getCategoryName = (category) => {
  return categoryMap[category] || category
}

const filteredProducts = computed(() => {
  let result = products.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(p => 
      p.name.toLowerCase().includes(keyword) ||
      (p.description || '').toLowerCase().includes(keyword)
    )
  }

  // 分类筛选
  if (filterCategory.value) {
    result = result.filter(p => p.category === filterCategory.value)
  }

  return result
})

const fetchProducts = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('/api/admin/products', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    if (response.data && response.data.success) {
      products.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogTitle.value = '添加产品'
  editingId.value = null
  form.value = {
    name: '',
    category: '',
    price: 0,
    image: '',
    description: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑产品'
  editingId.value = row.id
  form.value = {
    name: row.name,
    category: row.category,
    price: row.price,
    image: row.image || '',
    description: row.description || ''
  }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const token = localStorage.getItem('token')
    await axios.delete(`/api/admin/products/${row.id}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    ElMessage.success('删除成功')
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除产品失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    const token = localStorage.getItem('token')
    const data = {
      name: form.value.name,
      category: form.value.category,
      price: Number(form.value.price),
      image: form.value.image,
      description: form.value.description
    }

    if (editingId.value) {
      // 更新
      await axios.put(`/api/admin/products/${editingId.value}`, data, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      ElMessage.success('更新成功')
    } else {
      // 添加
      await axios.post('/api/admin/products', data, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchProducts()
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.product-manage {
  padding: 0;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

